package com.yqd.lesson.remote

import akka.actor.{Actor, ActorIdentity, ActorRef, Identify, ReceiveTimeout, Terminated}

import scala.concurrent.duration._

class LookUpActor(path:String) extends Actor {

  sendIdentifyRequest();

  def sendIdentifyRequest():Unit = {
    context.actorSelection(path) ! Identify(path)
    import context.dispatcher
    context.system.scheduler.scheduleOnce(3.seconds, self, ReceiveTimeout)
  }

  override def receive: Receive = {
    case ActorIdentity(`path`, Some(actor)) =>
      context.watch(actor)
      context.become(active(actor))
    case ActorIdentity(`path`, None) => println(s"Remote actor not available: $path")
    case ReceiveTimeout              => {
      sendIdentifyRequest()}
    case _                           => println("Not ready yet")
  }


  def active(actor: ActorRef): Actor.Receive = {
    case add:Add => {
      actor ! add}
    case AddResult(left:Int,right:Int,result:Int) => {
      println(s"${left} + ${right}=${result}")
    }
    case Terminated =>{
      println(s"${path} is dead");
      sendIdentifyRequest()
      context.become(receive)
    }
  }


}
